package org.dawning.shop.product.command.handler;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.model.Repository;
import org.axonframework.eventhandling.EventHandler;
import org.dawning.shop.common.commands.inventory.CreateInventoryCommand;
import org.dawning.shop.common.commands.product.CreateProductCommand;
import org.dawning.shop.common.events.product.ProductCreateEvent;
import org.dawning.shop.common.utils.BeanMapper;
import org.dawning.shop.product.command.aggregate.ProductAggregate;
import org.dawning.shop.common.utils.GenerateSku;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;

/**
 * Created by miou on 2017/6/12 0012.
 */
@Component
public class ProductHandler {

    private Logger logger = LoggerFactory.getLogger(ProductHandler.class);

    @Autowired
    private CommandGateway commandGateway;

    @Autowired
    @Qualifier("productAggregateRepository")
    private Repository<ProductAggregate> productAggregateRepository;

    @EventHandler
    public void on(CreateProductCommand createProductCommand) {
        logger.info("c create product command : "+createProductCommand.toString());
    }

    @EventHandler
    public void on(ProductCreateEvent event) {
        logger.info("c create product command : "+event.toString());
        event.getProduct().getItems().forEach((product) ->{
            logger.info("c create inventory command");
            //发送创建库存命令
            String inventoryId = GenerateSku.generateSku(event.getProductId(),product.getAttributes());
            commandGateway.send(new CreateInventoryCommand(inventoryId,product.getAmount(),product.getWarnAmount()));
        });
    }

}
